package com.bugstack.domain.activity.service.armory;

import com.bugstack.domain.activity.model.entity.ActivitySkuEntity;
import com.bugstack.domain.activity.reopsitory.IActivityRepository;
import com.bugstack.types.common.Constants;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: czb
 * @Description: 活动装配工厂
 * @DateTime: 2025/3/23 12:07
 **/
@Service
public class ActivityArmory implements IActivityDispatch, IActivityArmory {

    @Resource
    private IActivityRepository repository;

    @Override
    public boolean assembleActivitySku(Long sku) {
        //预热sku库存
        ActivitySkuEntity activitySkuEntity = repository.queryActivitySku(sku);
        cacheActivitySkuStockCount(sku, activitySkuEntity.getStockCount());
        //预热活动,首次查询会装配到内存
        repository.queryRaffleActivityByActivityId(activitySkuEntity.getActivityId());
        //预热活动次数配置
        repository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        return true;
    }

    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        List<ActivitySkuEntity> activitySkuEntities = repository.queryActivitySkuListByActivityId(activityId);
        activitySkuEntities.forEach(activitySkuEntity -> {
            cacheActivitySkuStockCount(activitySkuEntity.getSku(), activitySkuEntity.getStockCount());
            repository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        });
        repository.queryRaffleActivityByActivityId(activityId);
        return true;
    }

    private void cacheActivitySkuStockCount(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        repository.cacheActivitySkuStockCount(cacheKey, stockCount);
    }


    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return repository.subtractionActivitySkuStock(sku, cacheKey, endDateTime);
    }
}
